package org.cuijq.thinking.in.spring.bean.definition;

import org.cuijq.thinking.in.spring.ioc.domain.User;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 注解的bean
 */
//3.通过import
@Import(AnnotationBeanDefinitionDemo.Config.class)
public class AnnotationBeanDefinitionDemo {
    public static void main(String[] args) {
        //创建BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册
        applicationContext.register(AnnotationBeanDefinitionDemo.class);
       // Map<String, Config> beansOfbeans = applicationContext.getBeansOfType(Config.class);

        //通过beandefinition 注册api
        //1.命名方式
        registerUserBeanDefinition(applicationContext,"mercybiti-user");
        //2.非命名
        registerBeanDefinition(applicationContext);


        applicationContext.refresh();

        System.out.println("Config Beans所有bean实例"+applicationContext.getBeansOfType(Config.class));
        System.out.println("User Beans所有bean实例"+applicationContext.getBeansOfType(User.class));
        applicationContext.close();
    }

    //4.api
    public static void registerUserBeanDefinition(BeanDefinitionRegistry registry,String beanName){
        BeanDefinitionBuilder beanDefinitionBuilder=BeanDefinitionBuilder.genericBeanDefinition(User.class);
        beanDefinitionBuilder.addPropertyValue("id",1L)
                .addPropertyValue("name","cuijq");
        if (StringUtils.hasText(beanName)){
            registry.registerBeanDefinition(beanName,beanDefinitionBuilder.getBeanDefinition());
        }else {
            BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinitionBuilder.getBeanDefinition(),registry);
        }

    }
    public static void registerBeanDefinition(BeanDefinitionRegistry registry ){
        registerUserBeanDefinition(registry,null);
    }

    //2.通过 Component
    @Component
    public static class  Config{
        //1. 通过 @bean
        @Bean(name = {"user","cuijq-user"})
        public User user(){
            User user=new User();
            user.setId(1l);
            user.setName("cuijq");
            return user;
        }
    }


}
